package day03;

import day02.LoggerUtils;

import java.util.concurrent.*;

// -Xmx64m
// 模拟短信发送超时，但这时仍有大量的任务进入队列
public class TestOomThreadPool {
//    public static void main(String[] args) {
//        ExecutorService executor = Executors.newFixedThreadPool(2);
//        LoggerUtils.get().debug("begin...");
//        while (true) {
//            executor.submit(()->{
//                try {
//                    LoggerUtils.get().debug("send sms...");
//                    TimeUnit.SECONDS.sleep(30);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            });
//        }
//    }

    /**
     * 加入拒绝策略
     * @param args
     */
    public static void main(String[] args) {
        int poolSize = 2;
        int queueCapacity = 100; // 设置队列容量
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(queueCapacity);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ExecutorService executor = new ThreadPoolExecutor(
                poolSize,
                poolSize,
                0L,
                TimeUnit.MILLISECONDS,
                workQueue,
                threadFactory,
                handler
        );

        LoggerUtils.get().debug("begin...");
        while (true) {
            try {
                executor.submit(() -> {
                    try {
                        LoggerUtils.get().debug("send sms...");
                        TimeUnit.SECONDS.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            } catch (RejectedExecutionException e) {
                LoggerUtils.get().error("任务被拒绝，队列已满");
            }
        }
    }
}
